//-----------------------------------------------------------------------------
// File: ImageFormatter.cs
//
// Copyright (c) Dmitry Shuklin. All rights reserved.
//-----------------------------------------------------------------------------
using System;

namespace ObjectiveDraw.Platform.Serialization
{
	/// <summary>
	/// Summary description for ImageFormatter.
	/// </summary>
	public class ImageFormatter : IPropertyFormatter
	{
		public ImageFormatter()
		{
			//
			// TODO: Add constructor logic here
			//
		}
		#region IFieldFormatter Members

		public object SerializeValue(object value, object [] parameters)
		{
			using(System.IO.MemoryStream ms = new System.IO.MemoryStream())
			{
				if(value is System.Drawing.Image)
				{
					((System.Drawing.Image)value).Save(ms, System.Drawing.Imaging.ImageFormat.Png);
				}
				else
				{
					System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
					formatter.Serialize(ms, value);
				}
				return ms.ToArray();
			}
		}

		public object DeserializeValue(object value, object [] parameters)
		{
			object o = value;
			if(o is System.Drawing.Image)
			{
				return new System.Drawing.Bitmap((System.Drawing.Image)o);
			}
			if(o is System.Array)
			{
				using(System.IO.MemoryStream fs = new System.IO.MemoryStream((byte[])o))
				{
					using(System.Drawing.Image org = System.Drawing.Bitmap.FromStream(fs))
					{
						return new System.Drawing.Bitmap(org);
					}
				}
			}
			if(o is System.String)
			{
				string name = Convert.ToString(o);
				if(name==null || name.Length<1) return null;
				string path = System.IO.Path.Combine(Cerebrum.Windows.Forms.Application.Instance.ApplicationDirectory, name);
				if(!System.IO.File.Exists(path)) return null;
				using(System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
				{
					using(System.Drawing.Image org = System.Drawing.Bitmap.FromStream(fs))
					{
						return new System.Drawing.Bitmap(org);
					}
				}
			}
			return null;
		}

		#endregion
	}
}
